package com.lw.leetcode.bit.b;

/**
 * Created with IntelliJ IDEA.
 * 1947. 最大兼容性评分和
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/2 10:39
 */
public class MaxCompatibilitySum {

    public static void main(String[] args) {
        MaxCompatibilitySum test = new MaxCompatibilitySum();


        // 8
//        int[][] a1 = {{1, 1, 0}, {1, 0, 1}, {0, 0, 1}};
//        int[][] a2 = {{1, 0, 0}, {0, 0, 1}, {1, 1, 0}};

        // 0
        int[][] a1 = {{0, 0}, {0, 0}, {0, 0}};
        int[][] a2 = {{1, 1}, {1, 1}, {1, 1}};

        int i = test.maxCompatibilitySum(a1, a2);
        System.out.println(i);
    }


    private int[] ss;
    private int[] ms;
    private int m;
    private int n;
    private int max = 0;

    public int maxCompatibilitySum(int[][] students, int[][] mentors) {
        int m = students.length;
        int n = students[0].length;
        int[] ss = new int[m];
        int[] ms = new int[m];
        this.m = m;
        this.n = n;
        this.ss = ss;
        this.ms = ms;
        convert(students, ss);
        convert(mentors, ms);
        find(0, 0);
        return max;
    }

    private void find(int i, int sum) {
        if (i >= m) {
            max = Math.max(max, sum);
            return;
        }
        int c1 = ss[i];
        for (int j = 0; j < m; j++) {
            if (ms[j] == -1) {
                continue;
            }
            int c2 = ms[j];
            ms[j] = -1;
            int c = get(c1, c2);
            find(i + 1, sum + c);
            ms[j] = c2;
        }
    }

    private int get(int a, int b) {
        int c = 0;
        for (int i = 0; i < n; i++) {
            if ((a & 1) == (b & 1)) {
                c++;
            }
            a >>= 1;
            b >>= 1;
        }
        return c;
    }

    private void convert(int[][] old, int[] arr) {
        for (int i = 0; i < m; i++) {
            int[] ints = old[i];

            int item = 0;
            for (int j = 0; j < n; j++) {
                item = (item << 1) + ints[j];
            }
            arr[i] = item;
        }
    }

}
